// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: 'sleep-sign-0g9xr6lm95e07431',
});
const db = cloud.database()
const user_chaoxing = db.collection('user_chaoxing')
async function getConfigByUsername(username){
  // 没有记录,会抛出异常
  return user_chaoxing.doc(username).get()
}
async function setOrUpdateConfigByUsername(data) {
  if(data && data.corn_trigger && data.corn_trigger.length > 10){return;}
  console.log('符合条件')
  try {
      await getConfigByUsername(data._id);
      console.log(data,"开始更新")
      const _openid = data.userInfo.openId
      delete data.userInfo
    // 数据库中存在
    const { _id, ..._data } = data;
    user_chaoxing.doc(data._id).update({ data: {
        _openid,
        ..._data,
    } })
  } catch (ignored) {
    // 数据库中不存在 直接抛出异常
    user_chaoxing.add({ data, })
  }
}
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const log = cloud.logger()
  log.info({
      event,
  })
  setOrUpdateConfigByUsername(event)
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}